<#assign ctx=request.contextPath />
<#import '${ctx}/sys/include/head.html' as d/>
<#import '${ctx}/sys/include/body.html' as c/>
<#import '${ctx}/sys/include/table/toolbar.html' as t/>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="${ctx}/resource/js/jquery-3.5.0.js"></script>
<script type="text/javascript" src="${ctx}/resource/js/jquery.dsmorse-gridster.js"></script>
<script src="${ctx}/resource/antv/g2.v4.0.8.js"></script>
<script src="${ctx}/resource/antv/dataset.js"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/resource/css/jquery.dsmorse-gridster.min.css">
<@d.head title="仪表盘" />
<style type="text/css">
.gridster .gs-w {
  cursor: pointer;
  -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.gridster .player {
  -webkit-box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
  box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
  background: #BBB;
}
.gridster .gs-w.try {
  background-image: url(../img/sprite.png);
  background-repeat: no-repeat;
  background-position: 37px -169px;
}
.gridster .preview-holder {
  border: none !important;
  border-radius: 0 !important;
  background: red !important;
}
.gridster > ul > li > div {
	width: 95%;
	height: 80%;
	margin: 5px;
}
.gridster > ul > li > h2 {
	text-align: center;
	margin-top: 0.5em;
}
.bg-white {
	background-color: #ffffff;
}

.query-item {
	max-width: 150px;
	white-space: nowrap; /* 规定文本是否折行 */
	overflow: hidden; /* 规定超出内容宽度的元素隐藏 */
	text-overflow: ellipsis;
	display: inline-block;
	padding-right: 10px;
}

.search-item-dt {
	display: inline;
}

.search-item-dd {
	word-break: break-word;
	display: inline;
}

.search-item-dl {
	display: inline-block;
	max-height: 115px !important;
	line-height: 2em;
	word-break: break-word;
	/* overflow: hidden; */
	margin-bottom: 0;
	border-bottom-color: rgb(52, 55, 65);
}

.layui-layer-tips .layui-layer-content {
	color: #333 !important;
	background-color: #ece3e3 !important;
}

.layui-layer-tips i.layui-layer-TipsB, .layui-layer-tips i.layui-layer-TipsT
	{
	border-right-color: #ece3e3 !important;
}

.query-btn {
	padding: 0 10px;
	font-size: 12px;
}

.close-query {
	margin-left: -4px !important;
	position: absolute;
	color: #555;
	cursor: pointer;
	background-color: transparent;
}

.layui-layer-tips .layui-layer-content {
	box-shadow: 7px 7px 3px rgba(0, 0, 0, .2) !important;
}
</style>
<script type="text/javascript" src="${ctx}/resource/js/chart_draw.js"></script>
</head>
<@c.body>
	<div class="form" style="margin-top:12px;">
		<div class="layui-form-item" name="search_frame">
			<label class="layui-form-label">查询条件</label>
			<div class="layui-input-block" id="query_area">
				<div class="layui-btn" id="add_query">添加条件</div>
				<div class="layui-btn" id="save_dashboard">保存仪表盘</div>
			</div>
		</div>

	</div>
	<div class="gridster">
	    <ul>
	    </ul>
	</div>
</@c.body>
<script>
layui.extend({
	xmSelect: 'xm-select'
}).use(['appJs','form','layer','xmSelect','layer'],function(){
	var app = layui.appJs;
	var layer = layui.layer;
	var xmSelect = layui.xmSelect;
	var form = layui.form;


    var gridster;
    var charts = {};
    var dashboard_def;

    $(function () {

    	dashboard_def = {
				chart_def_ids:[5,6,7],
    			widget:[{"col":1,"row":1,"size_x":6,"size_y":4},{"col":1,"row":5,"size_x":6,"size_y":2},{"col":7,"row":1,"size_x":5,"size_y":6}]
    	}

    	var id = '${RequestParameters.id!""}';
		if(id != '') {
			app.async_ajax('get','${ctx}/biz/dashboard/def/get',{id:id},function(data){
				if(data.code == 0) {
					dashboard_def = JSON.parse(data.values.data.dashboardDef);
				}else {
					layer.msg(data.code+': '+data.msg);
					return;
				}
			});
		}
		dashboard_def.chart_defs=[];
		for(let id of dashboard_def.chart_def_ids) {
			app.async_ajax('get','${ctx}/biz/chart/def/find',{id:id},function(data){
				if(data.code == 0) {
					let chart_def = data.values.data;
					chart_def.chartDef = JSON.parse(chart_def.chartDef)
					dashboard_def.chart_defs.push(chart_def);
				}else {
					layer.msg(data.code+': '+data.msg);
					return;
				}
			});
		}



        gridster = $(".gridster > ul").gridster({
            widget_margins: [5, 5],
            widget_base_dimensions: [100, 100],
            helper: 'clone',
            resize: {
                enabled: true,
                stop: function (e, ui, $widget) {
					let chart_name = $widget.find("h2").html();
					let c = charts[chart_name];
					if(c) {
						c.destroy();
					}
					for(let op of dashboard_def.chart_defs) {
						if(op.name == chart_name) {
							app.ajax('post','${ctx}/biz/chart/data',{req:JSON.stringify(op.chartDef)},function(data){
					         	   if(data.code == 0) {
					             	  // var option = handleResponse(req,dimensionArray,metricArray,data.values.data);
					             	   let chart = new G2.Chart({
					     	           	    container: op.name,
					     	           	 	autoFit: true,
					     	           	    height: window.innerHeight - 250
					     	           	});
					             	  charts[op.name] = chart;
					             	   try{
					             		  draw(op.chartDef,chart,data);
					     	        	   //app.pic(chart,option);
					     	        	   chart.render();
					             	   }catch(e){
					             		   console.log(e)
					             		   layer.msg('解析出错');
					             	   }
					         	   }else {
					         		   layer.msg(data.code+': '+data.msg);
					         	   }
					            });
						}
					}
                }
            }
        }).data('gridster');

        let chart_length = dashboard_def.chart_defs.length;
        for(let i = 0;i<chart_length;i++) {
        	gridster.add_widget('<li><h2>'+dashboard_def.chart_defs[i].name+'</h2><hr/><div id="'+dashboard_def.chart_defs[i].name+'"></div></li>', dashboard_def.widget[i].size_x,dashboard_def.widget[i].size_y,dashboard_def.widget[i].col,dashboard_def.widget[i].row);
        }

        $('.js-seralize').on('click', function () {
            var s = gridster.serialize();

            $('#log').val(JSON.stringify(s));
        });

        $.each($(".gridster > ul > li > div"),function(i,h){
        	let req = dashboard_def.chart_defs[i];
        	app.ajax('post','${ctx}/biz/chart/data',{req:JSON.stringify(req.chartDef)},function(data){
         	   if(data.code == 0) {
             	  // var option = handleResponse(req,dimensionArray,metricArray,data.values.data);
             	   let chart = new G2.Chart({
     	           	    container: req.name,
     	           	 	autoFit: true,
     	           	    height: window.innerHeight - 250
     	           	});
             	  charts[req.name] = chart;
             	   try{
             		  draw(req.chartDef,chart,data);
     	        	   //app.pic(chart,option);
     	        	   chart.render();
             	   }catch(e){
             		   console.log(e)
             		   layer.msg('解析出错');
             	   }
         	   }else {
         		   layer.msg(data.code+': '+data.msg);
         	   }
            });
        });
    });

    let query_div = '<div id="field_select" class="xm-select-demo" style="width:380px;margin-bottom:3px;"></div>'+
	'<div class="layui-form">'+
		'<div class="layui-inline" style="width:90px;">'+
			'<select>'+
			'<option value="=">等于</option>'+
			'<option value=":">包含</option>'+
			'<option value=">">大于</option>'+
			'<option value="<">小于</option>'+
			'</select>'+
		'</div>'+
		'<div class="layui-input-inline" style="width:280px;margin-left: 12px;margin-right: 5px;position: initial;">'+
			'<input name="query_value" type="text" class="layui-input"></input>'+
		'</div>'+
		'<div class="layui-btn-group layui-input-inline"><a class="layui-btn layui-btn-primary query-btn" id="query_confirm"><i class="layui-icon">&#xe654;</i></a></div>'+
	'</div>';
	$("#add_query").unbind('click');
	$("#add_query").bind('click',function(){
		var layerIndex = layer.open({
			type:4,
			content:[query_div,'#add_query'],
			shade: 0,
			tips:3,
			skin: 'demo-class',
			area:['480px','100px']
		});
		var field_select = xmSelect.render({
			el: '#field_select',
			radio: true,
			clickClose: true,
			filterable: true,
			remoteSearch: true,
			remoteMethod: function(val, cb, show){
				//这里引入了一个第三方插件axios, 相当于$.ajax
				$.get('${ctx}/biz/data/ds/fields',{id: $("input[name='dsId']").val(),key:val},function(data){
				try{
					var res = data.values;
					cb(res.data)
				}catch(err){
					cb([]);
				}
				});
				},
			model: {
				label: {
					type: 'text',
					text: {
						left: '',
						right: '',
						separator: ', ',
					}
				}
			},
			data: []
		});
		$("#query_confirm").unbind('click');
		$("#query_confirm").bind('click',function(){
			let field_name = field_select.getValue("name");
			let op = $(this).parent().parent().find("div>select>option:selected").val();
			let value = $(this).parent().parent().find("input[name='query_value']").val();
			addQuery(field_name,op,value);
			queryItemAction();
			layer.msg(field_name+op+value);
			layer.close(layerIndex);
			//do search
			drawPic(buildQueryParam());
		});
		form.render('select');
	});

	function addQuery(field,op,value) {
		let q = $('<div class="layui-btn layui-btn-radius layui-btn-primary" style="cursor: auto;"></div>');
		let hidden = $("<div name='query_cmd' stype='display:hidden'></div>");
		hidden.attr("field",field);
		hidden.attr("op",op);
		hidden.attr("value",value);
		q.append($("<div class='query-item'></div>").html(field+op+value));
		q.append($('<span class="layui-badge-dot close-query">X</span>'));
		q.append(hidden);
		$("#query_area").prepend(q);
		$("#query_area");
	}

	function buildQueryParam() {
		let param = {};
		param.datasource = $("#dsId").val();
		let item = $("div[name='query_cmd']");
		for(let i of item) {
			let f = $(i).attr("field");
			let o = $(i).attr("op");
			let v = $(i).attr("value");
			let pack = {field:f,op:o,value:v};
			if(!param.must) {
				param.must = [];
			}
			param.must.push(pack);
		}
		return param;
	}

	function queryItemAction() {
		$(".close-query").unbind('click');
		$(".close-query").bind('click',function(){
			$(this).parent().remove();
		});
		$(".query-item").unbind('mouseenter').unbind('mouseleave');
		$(".query-item").bind('mouseenter',function(){
			let l = layer.tips($(this).html(),this,{tips:3});
			$(this).data('index',l);
		}).bind('mouseleave',function(){
			layer.close($(this).data('index'));
		});
	}

	$("#save_dashboard").bind('click',function(){
		var s = gridster.serialize();
		dashboard_def.widget = s;
        layer.prompt({title: '请保存：'}, function(text, index){
        	$.post("${ctx}/biz/dashboard/def/save",{name:text,dashboardDef:JSON.stringify(dashboard_def)},function(data){
            	layer.msg(data.code+":"+data.msg);
            })
		 });

	})
})
</script>
